﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace rf200_telecontrol_upper
{
    public partial class mainForm : Form
    {
        public static bool key0, left_rocker_key, right_rocker_key;
        public static bool up, down, left, right, X, Y, A, B;
        public static UInt16 left_rocker_x, left_rocker_y, right_rocker_x, right_rocker_y;

        public mainForm()
        {
            InitializeComponent();
        }

        private void comboBox_serialport_SelectedIndexChanged(object sender, EventArgs e)
        {
            serialPort.PortName = comboBox_serialport.Text;
        }

        private void comboBox_serialport_Click(object sender, EventArgs e)
        {
            comboBox_serialport.Items.Clear();
            comboBox_Port_Update();
        }

        private void comboBox_Port_Update()
        {
            comboBox_serialport.Items.Clear();
            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                foreach (string sName in sSubKeys)
                {
                    string sValue = (string)keyCom.GetValue(sName);
                    comboBox_serialport.Items.Add(sValue);
                }
            }
        }

        private void system_startup_Click(object sender, EventArgs e)
        {
            if (!serialPort.IsOpen)
            {
                if (comboBox_serialport.Text != "")
                    try
                    {
                        serialPort.Open();
                    }
                    catch
                    {
                        MessageBox.Show("串口" + serialPort.PortName + "打开失败！");
                        return;
                    }
                else
                {
                    MessageBox.Show("请选择串口");
                    return;
                }
            }
            else
            {
                MessageBox.Show("串口已打开，请检查串口占用");
                return;
            }

            comboBox_serialport.Enabled = false;
            system_startup.Enabled = false;
            button_serialclose.Enabled = true;
            MessageBox.Show("启动成功");
            Task.Factory.StartNew(new Action(() =>
            {
                receivemsg();   //循环接收函数
            }));
        }

        private void receivemsg()
        {
            int receive_length = 0;
            byte[] receive_data = new byte[60];
            while (true)
            {
                try
                {
                    receive_length = serialPort.Read(receive_data, 0, serialPort.BytesToRead);//读取的字节数
                    Thread.Sleep(5);//延迟5ms

                    data.data_decode(receive_data, receive_length);////调用数据解析函数
                    for (int k = 0; k < receive_length; k++)
                        richTextBox_receive.AppendText(receive_data[k].ToString("X2") + " ");
                    if (receive_length != 0)
                        richTextBox_receive.AppendText("\r\n");
                    Thread.Sleep(5);//延迟5ms

                    receive_data.Initialize();//初始化接收数据
                    receive_length = 0;//初始化字节长度

                    update_textbox();//更新显示
                }
                catch
                {

                }
            }
        }

        public void update_textbox()
        {
            textBox_key0.Text = key0.ToString();
            textBox_left_rocker_key.Text = left_rocker_key.ToString();
            textBox_right_rocker_key.Text= right_rocker_key.ToString();
            textBox_up.Text = up.ToString();
            textBox_down.Text = down.ToString();
            textBox_left.Text = left.ToString();
            textBox_right.Text = right.ToString();
            textBox_X.Text = X.ToString();
            textBox_Y.Text = Y.ToString();
            textBox_A.Text = A.ToString();
            textBox_B.Text = B.ToString();
            textBox_left_rocker_x.Text = left_rocker_x.ToString();
            textBox_left_rocker_y.Text = left_rocker_y.ToString();
            textBox_right_rocker_x.Text = right_rocker_x.ToString();
            textBox_right_rocker_y.Text = right_rocker_y.ToString();
        }

        private void button_serialclose_Click(object sender, EventArgs e)
        {
            comboBox_serialport.Enabled = true;
            system_startup.Enabled = true;
            serialPort.Close();
        }

        private void button_send_data_Click(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
            {
                string[] send_data = richTextBox_data.Text.Split();  //分割输入的字符串，判断有多少个字节需要发送
                int send_length = send_data.Length;
                byte[] buff = new byte[send_length];

                for (int i = 0; i < send_length; i++)
                {
                    buff[i] = byte.Parse(send_data[i], System.Globalization.NumberStyles.HexNumber); //格式化字符串为十六进制数值
                }

                try
                {
                    serialPort.Write(buff, 0, buff.Length);    //写数据
                    //Task.Run(() => printf_data(buff, Buff_Len, 0));
                    for (int k = 0; k < send_length; k++)
                        richTextBox_send.AppendText(buff[k].ToString("X2") + " ");
                    if (send_length != 0)
                        richTextBox_send.AppendText("\r\n");
                }
                catch
                {
                    MessageBox.Show("发送失败！！");
                }
            }
            else
            {
                MessageBox.Show("串口未打开！");
            }

        }

        private void button_clear_Click(object sender, EventArgs e)
        {
            if ((Button)sender == button_clear1)
                richTextBox_send.Clear();
            else if ((Button)sender == button_clear2)
                richTextBox_receive.Clear();
        }

        private void button_save_Click(object sender, EventArgs e)
        {
            data.save_data_dialog((Button)sender == button_save1 ?
                richTextBox_send : richTextBox_receive);
        }
    }
}
